<?php

namespace common\models;

use common\config\TimeFormator;
use common\service\transaction\Eth;
use Yii;
use yii\web\NotFoundHttpException;

/**
 * This is the model class for table "ico_order".
 *
 * @property string $id
 * @property string $ico_project_id
 * @property string $count
 * @property integer $status
 * @property string $trade_no
 * @property string $return_trade_no
 * @property integer $created_at
 * @property integer $updated_at
 * @property string $recieve_address
 * @property string $send_address_time
 * @property string $statusLabel
 * @property integer $uid
 * @property IcoProject $project
 * @property IcoMember $member
 * @property string $money
 */
class IcoOrder extends \common\models\BaseActiveRecord
{

    /**
     * 未转账
     */
    const STATUS_NOT_PAY = 0;

    /**
     * 转账中
     */
    const STATUS_PAY_ING = 1;

    /**
     * 待确认
     */
    const STATUS_NEED_OK = 2;

    /**
     * 等待填写收币地址
     */
    const STATUS_NEED_ADDRESS = 3;

    /**
     * 等待发币
     */
    const STATUS_NEED_SEND = 4;

    /**
     * 已退款
     */
    const STATUS_RETURN = 5;

    /**
     * 发币中
     */
    const STATUS_SEND_ING = 6;

    /**
     * 已完成
     */
    const STATUS_COMPLETE = 7;

    public static $statusMap = [
        '' => '全部',
        self::STATUS_NOT_PAY => '未转账',
        self::STATUS_PAY_ING => '转账中',
        self::STATUS_NEED_OK => '转账已成功，等待客服统计',
        self::STATUS_NEED_ADDRESS => '等待填写收币地址',
        self::STATUS_NEED_SEND => '待发币',
        self::STATUS_RETURN => '已退款',
        self::STATUS_SEND_ING => '发币中',
        self::STATUS_COMPLETE => '已完成',
    ];

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'ico_order';
    }

    public function fields()
    {
        $data = parent::fields();
        return $data;
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['ico_project_id', 'count', 'status', 'created_at','uid', 'updated_at'], 'integer'],
            [['ico_project_id','trade_no'], 'required'],
            [['send_address_time','money'], 'safe'],
            [['trade_no', 'return_trade_no', 'recieve_address'], 'string', 'max' => 1000],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '订单号',
            'ico_project_id' => '项目id',
            'count' => '数量',
            'status' => '状态',
            'statusLabel' => '状态',
            'trade_no' => '打款交易号',
            'return_trade_no' => '退款交易号',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'recieve_address' => '收币地址',
            'uid' => '用户ID',
            'money' => '转账金额',
            'send_address_time' => '发币时间',
        ];
    }

    /**
     * @return mixed
     */
    public function getStatusLabel()
    {
        return self::$statusMap[$this->status];
    }

    /**
     * @param bool $insert
     * @return bool
     * @throws NotFoundHttpException
     */
    public function beforeSave($insert)
    {
        if($insert){
            //判断数量是否够
            $project = IcoProject::findOne($this->ico_project_id);
            if(empty($project)){
                throw new NotFoundHttpException('项目不存在！');
            }
            if($project->start_time<time()){
                throw new NotFoundHttpException('项目未开始！');
            }
            if($project->end_time<time()){
                throw new NotFoundHttpException('项目已结束！');
            }
            list($tradeStatus,$money) = Eth::getTransStatus($this->trade_no);
            if(in_array($tradeStatus,[Eth::STATUS_NOT_EXIST,Eth::STATUS_FAILED])){
                throw new \Exception('交易有延迟，请过两分钟再次提交~');
            }
            if($tradeStatus==Eth::STATUS_COMPLETE){
                $this->money = $money;
            }
            $hasOrderCount = self::find()
                ->where([
                    'status'=>self::STATUS_NEED_SEND,
                    'ico_project_id'=>$this->ico_project_id
                ])->sum('count');
            $leftCount = $project->count - $hasOrderCount;
            if($this->count>$leftCount){
                throw new NotFoundHttpException('剩余可投数量不足！');
            }
        }
        if($this->status==self::STATUS_SEND_ING && $this->oldAttributes['status']!=$this->status){
            $this->send_address_time = time();
        }
        if($this->status==self::STATUS_RETURN && $this->oldAttributes['status']!=$this->status){
            if(empty($this->return_trade_no)){
                throw new NotFoundHttpException('退款交易号未填写！');
            }
        }

        //扣除库存
        if($this->status==self::STATUS_NEED_ADDRESS && $this->oldAttributes['status']!=$this->status){
//            $this->project->current_count = doubleval($this->project->current_count) + doubleval($this->count);
            $this->project->left_count = $this->project->current_count - $this->count;
            $this->project->save();
        }
        return parent::beforeSave($insert);
    }

    public function getProject()
    {
        return $this->hasOne(IcoProject::className(),['id'=>'ico_project_id']);
    }

    public function getMember()
    {
        return $this->hasOne(IcoMember::className(),['id'=>'uid']);
    }
}
